package linc.fun.openai.openai.listener;


import linc.fun.openai.constants.ApplicationConstants;
import linc.fun.openai.domain.vo.ChatReplyMessageVO;
import linc.fun.openai.exception.BizException;
import linc.fun.openai.util.ObjectMapperUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.jetbrains.annotations.Nullable;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.util.Objects;

/**
 * @author linc
 * @date 2023-3-24
 * ResponseBodyEmitter 消息流监听
 */
@Slf4j
@AllArgsConstructor
public class ResponseBodyEmitterStreamListener extends AbstractStreamListener {

    private final ResponseBodyEmitter emitter;

    @Override
    public void onMessage(String newMessage, String receivedMessage, ChatReplyMessageVO chatReplyMessageVO, int messageCount) {
        if (Objects.isNull(chatReplyMessageVO)) {
            return;
        }
        try {
            String msg = String.format("%s%s", messageCount != 1 ? ApplicationConstants.CHAT_MESSAGE_SPLIT_KEY : "", ObjectMapperUtil.toJson(chatReplyMessageVO));
            emitter.send(msg);
        } catch (Exception e) {
            log.warn("消息发送异常，第{}条消息，消息内容：{}", messageCount, receivedMessage, e);
            throw BizException.MESSAGE_SEND_ERROR;
        }
    }

    public static void main(String[] args) {
        ChatReplyMessageVO vo = new ChatReplyMessageVO();
        vo.setId("13b47218-8eb4-4999-84a8-052c9f6d2e99");
        vo.setParentMessageId("e65b6770-8433-46a6-a907-9d1aaebc5d49");
        vo.setConversationId("cfb4d8ae-239c-4f50-8a90-0bcb1f6cccb3");
        vo.setText("Java\ndasdasd\n");
        int messageCount = 2;
        System.out.println((messageCount != 1 ? "\n" : "") + ObjectMapperUtil.toJson(vo));
    }

    @Override
    public void onComplete(String receivedMessage) {
        emitter.complete();
    }

    @Override
    public void onError(String receivedMessage, Throwable t, @Nullable Response response) {
        try {
            ChatReplyMessageVO chatReplyMessageVO = new ChatReplyMessageVO();
            chatReplyMessageVO.setText(receivedMessage.concat("\n【接收消息处理异常，响应中断】"));
            emitter.send(ObjectMapperUtil.toJson(chatReplyMessageVO));
        } catch (Exception e) {
            log.warn("消息发送异常，处理异常发送消息时出错", e);
        } finally {
            try {
                emitter.complete();
            } catch (Exception ignored) {

            }
        }
    }
}
